#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Final build script for PDF Splitter Windows executable.
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def run_command(cmd, cwd=None):
    """Run command and return result."""
    print(f"Running: {' '.join(cmd) if isinstance(cmd, list) else cmd}")
    result = subprocess.run(cmd, cwd=cwd, shell=isinstance(cmd, str), capture_output=False)
    return result.returncode == 0

def main():
    """Main build process."""
    print("=" * 60)
    print("PDF Splitter Final Build Script")
    print("=" * 60)

    # Ensure we're in the right directory
    os.chdir(Path(__file__).parent)
    print(f"Working directory: {Path.cwd()}")

    # Clean previous builds
    print("\n[1/4] Cleaning previous builds...")
    for dir_name in ["build", "dist"]:
        dir_path = Path(dir_name)
        if dir_path.exists():
            shutil.rmtree(dir_path)
            print(f"   Removed {dir_path}")

    # Build the executable
    print("\n[2/4] Building executable...")

    # Build command as list to avoid shell escaping issues
    cmd = [
        "uv", "run", "pyinstaller",
        "--windowed",
        "--onefile",
        "--name", "PDF_Splitter",
        "--add-data", "src/pdf_splitter/i18n;pdf_splitter/i18n",
        "--hidden-import", "PyQt6.QtCore",
        "--hidden-import", "PyQt6.QtGui",
        "--hidden-import", "PyQt6.QtWidgets",
        "--hidden-import", "fitz",
        "--hidden-import", "pdf_splitter.i18n",
        "--hidden-import", "pdf_splitter.i18n.simple_translations",
        "--hidden-import", "pdf_splitter.i18n.languages",
        "--hidden-import", "pdf_splitter.i18n.translator",
        "src/pdf_splitter/main.py"
    ]

    if run_command(cmd):
        print("   Build successful!")
    else:
        print("   Build failed!")
        sys.exit(1)

    # Check results
    print("\n[3/4] Checking results...")
    exe_path = Path("dist/PDF_Splitter.exe")
    if not exe_path.exists():
        print("   Error: PDF_Splitter.exe not found!")
        sys.exit(1)

    # Get file info
    size_mb = exe_path.stat().st_size / 1024 / 1024
    print(f"   Executable: {exe_path.absolute()}")
    print(f"   Size: {size_mb:.1f} MB")

    # Create output directory with version
    print("\n[4/4] Creating release package...")
    version = "0.1.0"
    release_dir = Path(f"release_{version}")
    release_dir.mkdir(exist_ok=True)

    # Copy executable
    release_exe = release_dir / f"PDF_Splitter_v{version}.exe"
    shutil.copy2(exe_path, release_exe)
    print(f"   Copied to: {release_exe}")

    # Create README for release
    readme_content = f"""PDF Splitter v{version}
=====================

A cross-platform PDF file splitter application.

Installation:
1. Double-click PDF_Splitter_v{version}.exe to run
2. No installation required (portable version)

Usage:
- Drag and drop PDF files onto the window
- Use File > Open to load a PDF
- Select pages and use Split menu
- Switch between English and Chinese via Language menu

For more information, visit: https://gitcode.com/beinimaliesi/PDF_Splitter

Created with PyQt6 and PyMuPDF
"""

    readme_path = release_dir / f"README_v{version}.txt"
    with open(readme_path, "w", encoding="utf-8") as f:
        f.write(readme_content)
    print(f"   Created README: {readme_path}")

    # Success message
    print("\n" + "=" * 60)
    print("Build completed successfully!")
    print("=" * 60)
    print(f"\nExecutable ready:")
    print(f"  {exe_path.absolute()}")
    print(f"\nRelease package:")
    print(f"  {release_dir.absolute()}")
    print(f"\nTo test: Run {release_exe}")

    # Optional: Ask about creating installer
    print("\n" + "-" * 60)
    print("To create a Windows installer:")
    print("1. Install Inno Setup from https://jrsoftware.org/isdl.php")
    print("2. Run: uv run python scripts/build_windows.py")
    print("3. Open PDF_Splitter.iss in Inno Setup")
    print("4. Click Build to create installer")

if __name__ == "__main__":
    main()